package sensor

import (
	//"encoding/binary"
	"fmt"
	//"strings"
	"time"
	//"unicode"
	//"log"
	//"math"
)


// TemperatureHumidityParser 温湿度数据解析器
type TemperatureHumidityParser struct {
	expectedLength int
}

func NewTemperatureHumidityParser(dataLength int) *TemperatureHumidityParser {
	return &TemperatureHumidityParser{
		expectedLength: dataLength,
	}
}

func (p *TemperatureHumidityParser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		return false
	}
	return data[0] == 'R' && 
	       data[p.expectedLength-2] == '\r' && 
	       data[p.expectedLength-1] == '\n'
}

func (p *TemperatureHumidityParser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid data format")
	}

	humidity_start := 2
	if (data[2] == '0') {
		humidity_start = 3
	}
	humidity := string(data[humidity_start:7])
	temperature := string(data[11:15])

	// 清理数据
	humidity = cleanString(humidity)
	temperature = cleanString(temperature)

	return &SensorData{
		SensorType: "temperature_humidity",
		Values: map[string]interface{}{
			"temperature": temperature,
			"humidity":    humidity,
		},
		RawData:   string(data),
		Timestamp: time.Now(),
	}, nil
}

// TemperatureOnlyParser 只返回温度的解析器
type TemperatureOnlyParser struct {
	expectedLength int
}

func NewTemperatureOnlyParser(dataLength int) *TemperatureOnlyParser {
	return &TemperatureOnlyParser{
		expectedLength: dataLength,
	}
}

func (p *TemperatureOnlyParser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		return false
	}
	return data[0] == 'R' &&
	       data[p.expectedLength-2] == '\r' &&
	       data[p.expectedLength-1] == '\n'
}

func (p *TemperatureOnlyParser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid data format")
	}

	// 只提取温度值，忽略湿度
	temperature := string(data[11:15])

	// 清理数据
	temperature = cleanString(temperature)

	return &SensorData{
		SensorType: "temperature_only",
		Values: map[string]interface{}{
			"temperature": temperature,
		},
		RawData:   string(data),
		Timestamp: time.Now(),
	}, nil
}


